<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { getCustomerList, Customer } from '@/api/customer';
import { formatToLocaleDateTime, formatCustomerStatus, formatCustomerType } from '@/utils/format';

const router = useRouter();

// 表格加载状态
const loading = ref(false);

// 客户列表表格数据
const tableData = ref<Customer[]>([]);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const totalPages = ref(0);

// 搜索条件
const searchForm = reactive({
  name: '',
  phone: '',
  id_number: '',
  manager_id: undefined as number | undefined,
  partner_id: undefined as number | undefined
});

// 状态选项
const statusOptions = [
  { label: '已录单', value: 1 },
  { label: '待处理', value: 3 },
  { label: '待面签', value: 4 },
  { label: '已签约', value: 5 },
  { label: '审核资料', value: 6 },
  { label: '风控审批', value: 7 },
  { label: '提级审批', value: 8 },
  { label: '项目上报', value: 9 },
  { label: '资方确认', value: 10 },
  { label: '确认托管资料', value: 11 },
  { label: '风控核实', value: 12 },
  { label: '费用核实', value: 13 },
  { label: '待放款', value: 14 },
  { label: '放款待确认', value: 15 },
  { label: '资料待入库', value: 16 },
  { label: '待扣款', value: 17 },
  { label: '待解押', value: 18 },
  { label: '新行入押', value: 19 },
  { label: '银行放款', value: 20 },
  { label: '待还款', value: 21 },
  { label: '还款待核实', value: 22 },
  { label: '待完成', value: 23 },
  { label: '已完成', value: 24 },
  { label: '已取消', value: 25 }
];

// 初始化数据
onMounted(() => {
  fetchData();
});

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      page: currentPage.value,
      page_size: pageSize.value
    };

    const res = await getCustomerList(params);
    if (res.success) {
      tableData.value = res.data.list;
      total.value = res.data.total;
      totalPages.value = res.data.total_pages;
    } else {
      ElMessage.error(res.msg || '获取客户列表失败');
    }
  } catch (error) {
    console.error('获取客户列表出错:', error);
    ElMessage.error('获取客户列表出错');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  searchForm.phone = '';
  searchForm.id_number = '';
  searchForm.manager_id = undefined;
  searchForm.partner_id = undefined;
  currentPage.value = 1;
  fetchData();
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 处理每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchData();
};

// 格式化金额
const formatAmount = (amount) => {
  return amount ? `¥${amount.toLocaleString()}` : '-';
};

// 查看客户详情
const viewCustomerDetail = (row) => {
  router.push(`/business-manage/self-loan/detail/${row.id}`);
};

// 获取客户状态样式
const getStatusType = (status: number): 'primary' | 'success' | 'info' | 'warning' | 'danger' => {
  const statusTypeMap: Record<number, 'primary' | 'success' | 'info' | 'warning' | 'danger'> = {
    1: 'info',     // 已录单
    3: 'info',     // 待处理
    4: 'warning',  // 待面签
    5: 'primary',  // 已签约
    6: 'primary',  // 审核资料
    7: 'warning',  // 风控审批
    8: 'warning',  // 提级审批
    9: 'primary',  // 项目上报
    10: 'primary', // 资方确认
    11: 'primary', // 确认托管资料
    12: 'warning', // 风控核实
    13: 'primary', // 费用确认
    14: 'warning', // 待放款
    15: 'warning', // 放款待确认
    16: 'primary', // 资料待入库
    17: 'primary', // 待扣款
    18: 'primary', // 待解押
    19: 'warning', // 新行入押
    20: 'success', // 银行放款
    21: 'primary', // 待还款
    22: 'warning', // 还款待核实
    23: 'primary', // 待完成
    24: 'success', // 已完成
    25: 'danger'   // 已取消
  };
  return statusTypeMap[status] || 'info';
};
</script>

<template>
  <div class="self-loan-container">
    <!-- 搜索表单 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="searchForm" class="filter-form">
        <el-form-item>
          <el-input v-model="searchForm.name" placeholder="客户姓名" clearable @keyup.enter="handleSearch"
            style="width: 180px">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-input v-model="searchForm.phone" placeholder="手机号码" clearable @keyup.enter="handleSearch"
            style="width: 180px" />
        </el-form-item>

        <el-form-item>
          <el-input v-model="searchForm.id_number" placeholder="证件号码" clearable @keyup.enter="handleSearch"
            style="width: 180px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 内容区域 -->
    <el-card shadow="never" class="content-card">
      <template #header>
        <div class="card-header">
          <span>客户列表</span>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading" border
        :header-cell-style="{ background: '#f5f7fa' }">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="客户姓名" min-width="100" align="center" />
        <el-table-column prop="phone" label="联系电话" min-width="120" align="center" />
        <el-table-column label="客户类型" min-width="80" align="center">
          <template #default="{ row }">
            {{ formatCustomerType(row.customer_type) }}
          </template>
        </el-table-column>
        <el-table-column label="放款金额" min-width="120" align="right">
          <template #default="{ row }">
            {{ formatAmount(row.loan_amount) }}
          </template>
        </el-table-column>
        <el-table-column label="贷款时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatToLocaleDateTime(row.loan_time) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatToLocaleDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ formatCustomerStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewCustomerDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          background layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handlePageChange" />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.self-loan-container .filter-card {
  margin-bottom: 20px;
}

.self-loan-container .filter-form {
  display: flex;
  flex-wrap: wrap;
}

.self-loan-container .filter-form .el-form-item:last-child {
  margin-left: auto;
}

.self-loan-container .content-card {
  margin-top: 20px;
}

.self-loan-container .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.self-loan-container .pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>